package fr.obsmip.sedoo.core.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.obsmip.sedoo.core.domain.Log;

@Repository
public class LogDAOJPAImpl implements LogDAO{

	private static Logger logger = LoggerFactory.getLogger(LogDAOJPAImpl.class);
	
	protected EntityManager em;
    public EntityManager getEntityManager() {
	        return em;
	    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
	        this.em = entityManager;
	    }


	@Transactional
	public void add(Log log) 
	{
		getEntityManager().persist(log);
	}

	@Override
	public ArrayList<Log> findPage(int position, int pageSize) 
	{
		logger.debug("Position : "+position+" - Page size "+pageSize);
		List<Log> aux = em.createQuery("select log from Log log order by log.date desc").setFirstResult(position).setMaxResults(pageSize).getResultList();
		ArrayList<Log> resultList = new ArrayList<Log>(aux);
		return resultList;
	}

	@Override
	public int getHits() {
		
		Number  result=(Number) em.createQuery("select count(log.id) from Log log").getSingleResult();
		return result.intValue();
	}

	
	

	

}
